from flask import Blueprint, request, jsonify
from app.models.vector_search import VectorSearch
from app.utils.response import success_response, error_response
from flasgger import swag_from

bp = Blueprint('api', __name__)
vector_search = None

@bp.before_app_first_request
def initialize_vector_search():
    global vector_search
    vector_search = VectorSearch()

@bp.route('/address/vectorize', methods=['POST'])
@swag_from({
    'tags': ['地址向量化'],
    'summary': '订单地址向量化接口',
    'description': '批量处理订单地址向量化并存储',
    'parameters': [
        {
            'name': 'body',
            'in': 'body',
            'required': True,
            'schema': {
                'type': 'object',
                'properties': {
                    'orders': {
                        'type': 'array',
                        'items': {
                            'type': 'object',
                            'properties': {
                                'order_id': {
                                    'type': 'string',
                                    'description': '订单ID'
                                },
                                'user_id': {
                                    'type': 'string',
                                    'description': '用户ID'
                                },
                                'address': {
                                    'type': 'string',
                                    'description': '订单地址'
                                }
                            },
                            'required': ['order_id', 'user_id', 'address']
                        }
                    }
                }
            }
        }
    ],
    'responses': {
        200: {
            'description': '处理成功',
            'schema': {
                'type': 'object',
                'properties': {
                    'code': {
                        'type': 'integer',
                        'example': 200
                    },
                    'message': {
                        'type': 'string',
                        'example': 'success'
                    },
                    'data': {
                        'type': 'object',
                        'properties': {
                            'processed_count': {
                                'type': 'integer',
                                'description': '成功处理数量'
                            },
                            'failed_count': {
                                'type': 'integer',
                                'description': '失败数量'
                            },
                            'total_count': {
                                'type': 'integer',
                                'description': '总数量'
                            }
                        }
                    }
                }
            }
        }
    }
})
def vectorize_address():
    """订单地址向量化接口"""
    try:
        data = request.get_json()
        if not data or 'orders' not in data:
            return error_response('无效的请求数据')
        
        orders = data['orders']
        if not isinstance(orders, list):
            return error_response('orders必须是列表')
        
        # 验证订单数据
        for order in orders:
            if not all(k in order for k in ('order_id', 'user_id', 'address')):
                return error_response('订单数据格式不正确')
            if not all(isinstance(order[k], str) for k in ('order_id', 'user_id', 'address')):
                return error_response('order_id、user_id和address必须是字符串')
        
        processed_count, failed_count = vector_search.vectorize_addresses(orders)
        
        return success_response({
            'processed_count': processed_count,
            'failed_count': failed_count,
            'total_count': len(orders)
        })
        
    except Exception as e:
        return error_response(f'处理失败: {str(e)}')

@bp.route('/address/search', methods=['GET'])
@swag_from({
    'tags': ['地址查询'],
    'summary': '地址相似度查询接口',
    'description': '查询与给定地址相似度高于阈值的订单地址',
    'parameters': [
        {
            'name': 'address',
            'in': 'query',
            'type': 'string',
            'required': True,
            'description': '查询地址'
        },
        {
            'name': 'threshold',
            'in': 'query',
            'type': 'number',
            'format': 'float',
            'default': 0.85,
            'description': '相似度阈值(0-1)'
        },
        {
            'name': 'limit',
            'in': 'query',
            'type': 'integer',
            'default': 10,
            'description': '返回结果数量限制'
        }
    ],
    'responses': {
        200: {
            'description': '查询成功',
            'schema': {
                'type': 'object',
                'properties': {
                    'code': {
                        'type': 'integer',
                        'example': 200
                    },
                    'message': {
                        'type': 'string',
                        'example': 'success'
                    },
                    'data': {
                        'type': 'object',
                        'properties': {
                            'query_address': {
                                'type': 'string',
                                'description': '查询地址'
                            },
                            'threshold': {
                                'type': 'number',
                                'description': '相似度阈值'
                            },
                            'total_found': {
                                'type': 'integer',
                                'description': '找到的结果数量'
                            },
                            'results': {
                                'type': 'array',
                                'items': {
                                    'type': 'object',
                                    'properties': {
                                        'order_id': {
                                            'type': 'string',
                                            'description': '订单ID'
                                        },
                                        'user_id': {
                                            'type': 'string',
                                            'description': '用户ID'
                                        },
                                        'address': {
                                            'type': 'string',
                                            'description': '订单地址'
                                        },
                                        'similarity_score': {
                                            'type': 'number',
                                            'description': '相似度分数'
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
})
def search_address():
    """地址相似度查询接口"""
    try:
        address = request.args.get('address')
        threshold = request.args.get('threshold', default=0.85, type=float)
        limit = request.args.get('limit', default=10, type=int)
        
        if not address:
            return error_response('地址参数不能为空')
        if not 0 <= threshold <= 1:
            return error_response('threshold必须在0到1之间')
        if limit <= 0:
            return error_response('limit必须大于0')
        
        similar_addresses = vector_search.search_similar_addresses(
            address, threshold, limit
        )
        
        result = {
            'query_address': address,
            'threshold': threshold,
            'total_found': len(similar_addresses),
            'results': [
                {
                    'order_id': item['order_id'],
                    'user_id': item['user_id'],
                    'address': item['address'],
                    'similarity_score': item['similarity']
                }
                for item in similar_addresses
            ]
        }
        
        return success_response(result)
        
    except Exception as e:
        return error_response(f'搜索失败: {str(e)}') 